//! ISO8583服务器主程序
//! 重构后的版本，应用了多种设计模式和最佳实践

use log::{info, debug, error};
use simplelog;
use std::path::Path;
use std::sync::Arc;

use iso8583_rs::iso8583::iso_spec::{IsoMsg, spec};
use iso8583_rs::iso8583::IsoError;
use iso8583_rs::iso8583::mli::MLIType::MLI2E;
use iso8583_rs::iso8583::server::{ISOServer, MsgProcessor};

// 导入重构后的模块
mod config;
mod services;
mod handlers;

use config::Config;
use services::{ValidationService, ResponseBuilder};
use handlers::{MessageHandlerFactory, MessageHandleResult};

/// 重构后的消息处理器
/// 使用依赖注入和策略模式
pub struct EnhancedMsgProcessor {
    validation_service: Arc<ValidationService>,
    handler_factory: Arc<MessageHandlerFactory>,
}

impl EnhancedMsgProcessor {
    /// 创建新的增强消息处理器
    pub fn new(config: &Config) -> Self {
        let validation_service = Arc::new(ValidationService::new(config.default_key.clone()));
        let handler_factory = Arc::new(MessageHandlerFactory::default());
        
        Self {
            validation_service,
            handler_factory,
        }
    }

    /// 解析消息类型
    fn extract_message_type(&self, iso_msg: &IsoMsg) -> Result<String, IsoError> {
        iso_msg.get_field_value(&"message_type".to_string())
    }

    /// 记录性能指标
    fn log_performance_metrics(&self, iso_server: &ISOServer, start_time: std::time::Instant) {
        let elapsed = start_time.elapsed();
        iso_server.response_time_metric().update(elapsed.as_millis() as i64);
        
        if iso_server.txn_rate_metric().count() % 100 == 0 {
            info!(
                "TPS: {:.2}, 平均响应时间: {:.2}ms",
                iso_server.txn_rate_metric().one_minute_rate(),
                iso_server.response_time_metric().snapshot().mean()
            );
        }
    }

    /// 处理消息的核心逻辑
    fn process_message(
        &self,
        iso_server: &ISOServer,
        iso_msg: &IsoMsg,
        raw_msg: &[u8],
    ) -> Result<MessageHandleResult, IsoError> {
        let message_type = self.extract_message_type(iso_msg)?;
        debug!("处理消息类型: {}", message_type);

        self.handler_factory.handle_message(
            &message_type,
            iso_msg,
            raw_msg,
            &self.validation_service,
        )
    }
}

impl MsgProcessor for EnhancedMsgProcessor {
    fn process(&self, iso_server: &ISOServer, msg: &mut Vec<u8>) -> Result<(Vec<u8>, IsoMsg), IsoError> {
        let start_time = std::time::Instant::now();
        
        // 解析消息
        let iso_msg = iso_server.spec.parse(msg)
            .map_err(|e| {
                error!("消息解析失败: {}", e.msg);
                IsoError { msg: e.msg }
            })?;

        debug!(
            "成功解析消息: {} \n解析结果:\n{}\n",
            iso_msg.msg.name(),
            iso_msg
        );

        // 标记事务
        iso_server.txn_rate_metric().mark(1);

        // 处理消息
        let handle_result = self.process_message(iso_server, &iso_msg, msg)?;
        
        // 组装响应
         let response_data = match handle_result.response_msg.assemble() {
             Ok(data) => data,
             Err(e) => {
                 error!("响应消息组装失败: {}", e.msg);
                 return Err(IsoError {
                     msg: format!("响应组装失败: {}", e.msg),
                 });
             }
         };

        // 记录性能指标
        self.log_performance_metrics(iso_server, start_time);

        // 记录STAN
        if let Ok(stan) = handle_result.response_msg.get_field_value(&"11".to_string()) {
            debug!("STAN: {}", stan);
        }

        Ok((response_data, handle_result.response_msg))
    }
}

/// 应用程序配置和初始化
struct Application {
    config: Config,
}

impl Application {
    fn new() -> Self {
        Self {
            config: Config::default(),
        }
    }

    /// 初始化日志系统
    fn init_logging(&self) -> Result<(), Box<dyn std::error::Error>> {
        simplelog::SimpleLogger::init(
            simplelog::LevelFilter::Debug,
            simplelog::Config::default(),
        )?;
        Ok(())
    }

    /// 设置规范文件环境变量
    fn setup_spec_file(&self) {
        let path = Path::new(".")
            .join("src")
            .join("sample_spec.yaml");
        
        if let Some(spec_file) = path.to_str() {
            std::env::set_var("SPEC_FILE", spec_file);
        }
    }

    /// 创建ISO服务器
      fn create_server(&self) -> Result<ISOServer, Box<dyn std::error::Error>> {
          let iso_spec = spec("");
          let server_address = format!("{}:{}", self.config.server_address, self.config.server_port);
          
          info!(
              "启动ISO服务器 - 规范: {}, 地址: {}",
              iso_spec.name(),
              server_address
          );

          let msg_processor = Box::new(EnhancedMsgProcessor::new(&self.config));
          
          ISOServer::new(server_address, iso_spec, MLI2E, msg_processor)
               .map_err(|e| format!("服务器创建失败: {}", e.msg).into())
      }

    /// 运行应用程序
    fn run(&self) -> Result<(), Box<dyn std::error::Error>> {
        // 初始化日志
        self.init_logging()?;
        
        // 设置规范文件
        self.setup_spec_file();
        
        // 创建并启动服务器
         let server = self.create_server()?;
        
        info!("ISO8583服务器启动成功，开始监听连接...");
        
        // 启动服务器（阻塞调用）
        server.start().join()
            .map_err(|e| format!("服务器运行错误: {:?}", e))?;
        
        Ok(())
    }
}

fn main() {
    let app = Application::new();
    
    if let Err(e) = app.run() {
        error!("应用程序运行失败: {}", e);
        std::process::exit(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_application_creation() {
        let app = Application::new();
        assert_eq!(app.config.server_port, 6666);
    }

    #[test]
    fn test_enhanced_msg_processor_creation() {
        let config = Config::default();
        let processor = EnhancedMsgProcessor::new(&config);
        // 验证处理器创建成功
        assert!(Arc::strong_count(&processor.validation_service) >= 1);
    }
}


